#!/bin/bash
OPTIONS=`getopt -o afdhlD \
    --long all,file,dir,help,list,deep \
    -n 'example.bash' -- "$@"`
if [ $? != 0 ] ; then echo "terminating..." >&2 ; exit 1 ; fi

# note the quotes around `$temp': they are essential!
#set 会重新排列参数的顺序，也就是改变$1,$2...$n的值，这些值在getopt中重新排列过了
eval set -- "$OPTIONS"

# echo "======="
# echo "optout is $OPTIONS"            #这个变量没有用，只是为查看getopt 命令的输出
# echo "after set $@ " 
#经过getopt的处理，下面处理具体选项。
DEEP=0
DIR=""
TYPE=""
IS_FILE=0
IS_DIR=0
IS_ALL=0
IS_LIST=0

build_help()
{
    echo -e "\n\033[33moption chosice\n\033[0m"
    echo " -a --all  list dir and file with key params "
    echo " -f --file list file with key params "
    echo " -d --dir  list director with key params "
    echo " -h --help show help"
    echo " -l --list show all detail file or path message with key params "
    echo " -D --deep search deep path "
    echo -e "\n"
}

file_count()
{
    count=`ls -l ${LR} ${DIR}/ | grep "${TYPE}" | grep "^-" | wc -l`
    echo -e "\033[32m\033[1m file count: "$count" \033[0m"
    if [ ${IS_LIST} -eq 1 ];then
        echo -e "\033[33m\033[1m\n-------Detail------\n\033[0m"
        ls -l ${LR} ${DIR}/ | grep "${TYPE}" | grep "^-"
        echo -e "\033[33m\033[1m\n-------------------\n\033[0m"
    fi

}

dir_count()
{
    count=`ls -l ${LR} ${DIR}/ | grep "${TYPE}" | grep "^d" | wc -l`
    echo -e "\033[32m\033[1m dir count: "$count" \033[0m"
    if [ ${IS_LIST} -eq 1 ];then
        echo -e "\033[33m\033[1m\n-------Detail------\n\033[0m"
        ls -l ${LR} ${DIR}/ | grep "${TYPE}" | grep "^d"
        echo -e "\033[33m\033[1m\n-------------------\n\033[0m"
    fi
}

all_count()
{
    count=`ls -l ${LR} ${DIR}/ | grep "${TYPE}" | wc -l` 
    echo -e "\033[32m\033[1m all count: "$count" \033[0m"
    if [ ${IS_LIST} -eq 1 ];then
        echo -e "\033[33m\033[1m\n-------Detail------\n\033[0m"
        ls -l ${LR} ${DIR}/ | grep "${TYPE}"
        echo -e "\033[33m\033[1m\n-------------------\n\033[0m"
    fi
}

main()
{
    if [ ${IS_FILE} -eq 1 ];then
        file_count
    elif [ ${IS_DIR} -eq 1 ];then
        dir_count
    else
        all_count
    fi
}

while true ; do
        case "$1" in
                -a|--all) IS_ALL=1 ; shift ;;
                -f|--file) IS_FILE=1 ; shift ;;
                -d|--dir) IS_DIR=1 ; shift ;; 
                -h|--help) build_help break ; exit 0;;
                -l|--list) IS_LIST=1 ; shift ;;
                -D|--deep) DEEP=1 ; shift ;;
                --) shift ; break ;;
                *) echo "internal error!" ; exit 1 ;;
        esac
done
if [ ${DEEP} -eq 1 ];then
    LR="-R"
fi
DIR=$1
TYPE=$2

main
